#Type "ruby execute.rb" to execute.
#
#Usage Scenario -
#  You have been downloading a file using BitTorrent protocol, and
#  you find out that your friend has also been downloading the same torrent.
#  So, now you both have an incomplete copy of same file, but some blocks
#  may have been downloaded by him which you don't have.
#  So you execute this programme, which copies only the completed blocks, which
#  you miss.
module Com
module Googlecode
module VikrantIncubator
  
  def merge_incomplete
    puts "Enter source file."
    file1 = gets.strip
    puts "Enter destination file."
    file2 = gets.strip
    file2_size = File.size(file2)
    raise "Size mismatch" unless File.size(file1) == file2_size
    puts "Destination file is going to be modified! Ok?"
    gets
    index = 0
    replaced = 0
    size_to_read = 16 * 1024 #(16 KiB), standard bock size in BitTorrent.
    empty_chunk = "\000" * size_to_read
    f = File.open(file2, "r+b") #"b" if someone is on win$.
    while index < file2_size - size_to_read #Last chunk is not guaranteed to be of 16KiB, I guess.
      chunk1 = IO.read(file1, size_to_read, index)
      unless chunk1 == empty_chunk
        chunk2 = IO.read(file2, size_to_read, index)
        if chunk2 == empty_chunk
          puts "REPLACING block #{index/size_to_read+1} of total #{file2_size/size_to_read} blocks"
          f.seek index
          f.write chunk1
          replaced += size_to_read
        end
      end
      index += size_to_read;
    end
    f.close
    puts "ADDED around ~#{replaced/1024/1024} MBs."
  end

end
end
end
